﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Duoease.ContainerModel.Serialization;
using System.Xml;
using Duoease.ContainerModel.Entity;
using System.Drawing.Drawing2D;
using Duoease.ContainerModel.Utils;
using SmartMD.DataModel;

namespace Duoease.ContainerModel
{
    public partial class ContainerModelView : UserControl
    {
        #region 变量
        public ContainerModelView()
        {
            InitializeComponent();
        }

        public Graphics g = null;
        private bool m_disposed = false;
        public ToolTip mouseTip = new ToolTip();

      /*  private bool IsFridgeModel = false;
        private bool IsWFridgeModel = false;
        private bool IsYFridgeModel = false;*/

        public event MouseEventHandler fridgeClickHandler;
        public event MouseEventHandler shelfClickHandler;
        public event MouseEventHandler BoxModelMousedown;
        public event EventHandler MsgViewClick;
        public event EventHandler MsgGetOutClick;
        public event EventHandler MsgLoadClick;
        #endregion

        #region 属性
        private DocumentModel _docModel = new DocumentModel();
        public DocumentModel docmodel
        {
            get { return _docModel; }
            set
            {
                _docModel = value;
            }
        }

        /// <summary>
        /// 新建容器
        /// </summary>
        private bool _IsCreatNewModel = false;
        public bool IsCreatNewModel
        {
            get { return _IsCreatNewModel; }
            set
            {
                _IsCreatNewModel = value;
                if (_IsCreatNewModel)
                {
                    //_Xml = new XmlDocument();
                    this.docmodel.Xml = new XmlDocument();
                    _ctnNo = "";
                    _fridgeModel = null;
                    _shelfModel = null;
                    _boxModel = null;
                    _IceFullPercent = null;
                    _DrawerFullPercent = null;
                    _BoxIsFull = null;
                }
            }
        }
        /**
         * 容器规格
         * 
         * */
        public string specification = "";
        public string fridgeSpecification = "";
        public string shelfSpecification = "";
        public string boxSpecification = "";

        /// <summary>
        /// 容器编号
        /// </summary>
        private string _ctnNo = "";
        public string ctnNo
        {
            get { return _ctnNo; }
            set
            {
                _ctnNo = value;
            }
        }
        /**
         * 功能:容器选择
         * 
         * */
        private BaseModel _selectedItem = null;
        public BaseModel SelectedItem
        {
            get { return _selectedItem; }
            set { _selectedItem = value; }
        }
        private string _selectedItemID = "";
        public string SelectedItemID
        {
            get { return _selectedItemID; }
            set { _selectedItemID = value; }
        }

        /// <summary>
        /// 绑定FridgeModel
        /// </summary>
        private BaseModel _fridgeModel = null;
        public BaseModel FridgeModel
        {
            get { return _fridgeModel; }
            set
            {
                _fridgeModel = value;
                if (_fridgeModel != null)
                {
                    _fridgeModel.View = this;
                    _fridgeModel.panel = this.splitContainer1.Panel1;
                    this.docmodel.ConstructContainerXml(_fridgeModel);

                    _fridgeModel.Refresh();
                }
            }
        }

        /// <summary>
        /// 绑定ShelfModel
        /// </summary>
        private ShelfModel _shelfModel = null;
        public ShelfModel ShelfModel
        {
            get { return _shelfModel; }
            set
            {
                _shelfModel = value;
                if (_shelfModel != null)
                {
                    _shelfModel.View = this;
                    _shelfModel.panel = this.splitContainer2.Panel1;
                    this.docmodel.ConstructContainerXml(_shelfModel);
                    _shelfModel.Refresh();
                }
            }
        }

        /// <summary>
        /// 绑定BoxModel
        /// </summary>
        private BoxModel _boxModel = null;
        public BoxModel BoxModel
        {
            get { return _boxModel; }
            set
            {

                _boxModel = value;
                if (_boxModel != null)
                {
                    _boxModel.View = this;

                    _boxModel.panel = this.splitContainer2.Panel2;
                    this.docmodel.ConstructContainerXml(_boxModel);
                    _boxModel.Refresh();
                }
            }
        }

        /// <summary>
        /// 冰箱所有格存放状态比例值
        /// </summary>
        private double[,] _IceFullPercent = null;
        public double[,] IceFullPercent
        {
            get { return _IceFullPercent; }
            set
            {
                _IceFullPercent = value;
                if (FridgeModel != null)
                {
                    FridgeModel.StoredPercent = _IceFullPercent;
                    //this.splitContainer1.Panel1.Refresh();
                }
            }
        }

        /// <summary>
        /// 架子所有格存放状态比例值
        /// </summary>
        private double[,] _DrawerFullPercent = null;
        public double[,] DrawerFullPercent
        {
            get { return _DrawerFullPercent; }
            set
            {
                _DrawerFullPercent = value;
                if (ShelfModel != null)
                {
                    ShelfModel.StoredPercent = _DrawerFullPercent;
                    //this.splitContainer2.Panel1.Refresh();
                }
            }
        }

        /// <summary>
        /// 盒子所有格是否为空集合
        /// </summary>
        private bool[,] _BoxIsFull = null;
        public bool[,] BoxIsFull
        {
            get { return _BoxIsFull; }
            set
            {
                _BoxIsFull = value;
                if (BoxModel != null)
                {
                    BoxModel.IsFull = _BoxIsFull;
                    this.splitContainer2.Panel2.Refresh();
                }
            }
        }


        /// <summary>
        /// 鼠标获取行号
        /// </summary>       
        private int _MouseRow = -1;
        public int MouseRow
        {
            get { return _MouseRow; }
            set { _MouseRow = value; }
        }
        /// <summary>
        /// 鼠标获取列号
        /// </summary>       
        private int _MouseColumn = -1;
        public int MouseColumn
        {
            get { return _MouseColumn; }
            set { _MouseColumn = value; }
        }

        /// <summary>
        /// 盒子右键菜单是否启动
        /// </summary>
        private bool _IsShowContext = true;
        public bool IsShowContext
        {
            get { return _IsShowContext; }
            set
            {
                _IsShowContext = value;
                if (_IsShowContext)
                {

                    toolStripMenuItem1.Visible = true;
                    toolStripMenuItem2.Visible = true;
                    //toolSMI_MsgView.Visible = true;
                    //toolSMI_GetOut.Visible = true;
                    //toolSMI_Load.Visible = true;
                }
                else
                {
                    toolStripMenuItem1.Visible = false;
                    toolStripMenuItem2.Visible = false;
                    //toolSMI_MsgView.Visible = false;
                    //toolSMI_GetOut.Visible = false;
                    //toolSMI_Load.Visible = false;
                }
            }
        }
        #endregion

        #region 冰箱模型
        /**
         * 功能：panel.refresh时调用
         * 
         * */
        public int FridgeWidth = 0;
        public int FridgeHeight = 0;
        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {
            if (IsRemove)
            {
                e.Graphics.Clear(splitContainer1.Panel1.BackColor);
                FridgeModel = null;
                IsRemove = false;
            }
            else
            {
                if (FridgeModel != null)
                {
                    FridgeModel.g = e.Graphics;
                    FridgeModel.ContainerWidth = FridgeWidth;
                    FridgeModel.ContainerHeight = FridgeHeight;
                    FridgeModel.Draw();
                }
            }
        }
        /**
         * 功能：窗口大小自适应事件
         * 
         * */
        private void splitContainer1_Panel1_SizeChanged(object sender, EventArgs e)
        {
            leftlabel.Height = middlelabel.Height;
            FridgeWidth = this.splitContainer1.Panel1.Width;
            FridgeHeight = this.splitContainer1.Panel1.Height;

            if (FridgeModel != null)
            {
                FridgeModel.AffixToLabel(leftlabel, FridgeWidth, FridgeHeight);
            }
        }

        private void splitContainer2_Panel1_SizeChanged(object sender, EventArgs e)
        {
            ShelfWidth = this.splitContainer2.Panel1.Width;
            ShelfHeight = this.splitContainer2.Panel1.Height;

            if (ShelfModel != null)
            {
                ShelfModel.AffixToLabel(middlelabel, ShelfWidth, ShelfHeight);
            }

        }
        private void splitContainer2_Panel2_SizeChanged(object sender, EventArgs e)
        {
            BoxWidth = this.splitContainer2.Panel2.Width;
            BoxHeight = this.splitContainer2.Panel2.Height;

            if (BoxModel != null)
            {
                BoxModel.AffixToLabel(rightlabel, BoxWidth, BoxHeight);
            }
        }

        private void splitContainer1_Panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (FridgeModel != null)
            {
                FridgeModel.OnMouseOverHandler(sender, e);
            }
        }
        /**
         * 功能：点击冰箱
         * 
         * */
        private void splitContainer1_Panel1_MouseDown(object sender, MouseEventArgs e)
        {
            this.ShelfModel = null;
            this.BoxModel = null;
            if (FridgeModel != null)
            {
                FridgeModel.OnMouseClickHandler(sender, e);
            }
          
            if (ShelfModel != null)
            {
                ShelfModel.RefreshLabel("架子");
            }
            if (BoxModel != null)
            {
                BoxModel.RefreshLabel("盒子");
            }
          
            if (_fridgeModel != null)
            {
                XmlNode node = this.docmodel.Xml.SelectSingleNode("Container");
                string strDName = "ShelfModel" + _fridgeModel.ID + "-" + (MouseRow * 10 + MouseColumn).ToString();
                foreach (XmlNode xn in node)//遍历
                {
                    if (xn.Name == strDName)
                    {
                        ShelfModel shelfmodel = new ShelfModel();
                        shelfmodel.ParseXml(xn);
                        shelfmodel.Name = _fridgeModel.Name;
                        this.ShelfModel = shelfmodel;
                     
                        break;
                    }
                }
            }
            if (_shelfModel != null)
            {
                DrawerFullPercent = new double[_shelfModel.Row, _shelfModel.Column];
                //ShelfModel.GetModelPercent(ShelfModel.ID);
                _selectedItemID = ShelfModel.ID;
                _selectedItem = ShelfModel;
                this.fridgeClickHandler(sender, e);
                this.ShelfModel.Refresh();
            }
            else {
                //清空架子
                this.splitContainer2.Panel1.Controls.Clear();
                this.splitContainer2.Panel1.Refresh();
                //清空盒子
                this.splitContainer2.Panel2.Controls.Clear();
                this.splitContainer2.Panel2.Refresh();
            }
        }
        #endregion

        #region 架子
        public int ShelfWidth = 0;
        public int ShelfHeight = 0;
        private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
        {
            if (IsRemove)
            {
                e.Graphics.Clear(splitContainer2.Panel1.BackColor);
                ShelfModel = null;
                IsRemove = false;
            }
            else
            {
                if (ShelfModel != null)
                {
                    ShelfModel.g = e.Graphics;
                    ShelfModel.ContainerWidth = ShelfWidth;
                    ShelfModel.ContainerHeight = ShelfHeight;
                    ShelfModel.StoredPercent = DrawerFullPercent;
                    ShelfModel.Draw();
                }
            }
        }

        private void splitContainer2_Panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (ShelfModel != null)
            {
                ShelfModel.OnMouseOverHandler(sender, e);
            }
        }

        /**
         * 功能 ： 点击盒子
         * 
         * */
        private void splitContainer2_Panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.BoxModel != null)
            {
                this.BoxModel = null;
            }
           
            if (ShelfModel != null)
            {
                ShelfModel.OnMouseClickHandler(sender, e);
  
                if (this.BoxModel != null)
                {
                    this.ShelfModel.IsFull = new bool[this.BoxModel.Row, this.BoxModel.Column];
                   // this.ShelfModel.GetModelPercent(BoxModel.ID);
                    this.SelectedItemID = this.BoxModel.ID;
                    this.SelectedItem = this.BoxModel;
                    this.BoxModel.Name = _fridgeModel.Name;
                    shelfClickHandler(sender, e);
                }
                else
                {
                    this.splitContainer2.Panel2.Controls.Clear();
                    this.splitContainer2.Panel2.Refresh();
                }
            }

        }
        #endregion

        #region 盒子
        public int BoxWidth = 0;
        public int BoxHeight = 0;
        private bool IsRemove = false;
        private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
        {
            if (IsRemove)
            {
                e.Graphics.Clear(splitContainer2.Panel2.BackColor);
                BoxModel = null;
                IsRemove = false;
            }
            else
            {
                if (BoxModel != null)
                {
                    BoxModel.g = e.Graphics;
                    BoxModel.ContainerWidth = BoxWidth;
                    BoxModel.ContainerHeight = BoxHeight;
                    BoxModel.IsFull = BoxIsFull;
                    BoxModel.Draw();
                }
            }
        }

        private void splitContainer2_Panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (BoxModel != null)
            {
                BoxModel.g = this.splitContainer2.Panel2.CreateGraphics();
                BoxModel.OnMouseOverHandler(sender, e);
            }
        }
        /**
         * 功能：点击盒子的每个单元格
         *       多选功能
         * */
        private void splitContainer2_Panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (BoxModel != null)
            {
                BoxModel.OnMultiSelectedHandler(sender, e);
            }
        }
        #endregion

        #region 事件
        public void InewLabel_MouseDown(object sender, MouseEventArgs e)
        {
            MouseEventArgs me = new MouseEventArgs(e.Button, e.Clicks, e.X + (sender as Label).Location.X, e.Y + (sender as Label).Location.Y, e.Delta);
            splitContainer1_Panel1_MouseDown(sender, me);
        }

        public void DnewLabel_MouseDown(object sender, MouseEventArgs e)
        {
            MouseEventArgs me = new MouseEventArgs(e.Button, e.Clicks, e.X + (sender as Label).Location.X, e.Y + (sender as Label).Location.Y, e.Delta);
            splitContainer2_Panel1_MouseDown(sender, me);
        }

        public void BnewLabel_MouseDown(object sender, MouseEventArgs e)
        {
            MouseEventArgs me = new MouseEventArgs(e.Button, e.Clicks, e.X + (sender as Label).Location.X, e.Y + (sender as Label).Location.Y, e.Delta);
            splitContainer2_Panel2_MouseDown(sender, me);
        }

        /**
         * 功能:编辑架子
         * 
         * */
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string strModelID = _fridgeModel.ID;
            string strID = strModelID + "-" + (MouseRow * 10 + MouseColumn).ToString();
            EditModel editmodel = new EditModel(this, strID, 1);
            editmodel.Show();
        }
        /**
         * 功能：编辑盒子
         * 
         * */
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            string strID = _shelfModel.ID + "-" + (MouseRow * 10 + MouseColumn).ToString();
            EditModel editmodel = new EditModel(this, strID, 2);
            editmodel.Show();
        }

        private void toolSMI_MsgView_Click(object sender, EventArgs e)
        {
            this.MsgViewClick(sender, e);
        }

        private void toolSMI_GetOut_Click(object sender, EventArgs e)
        {
            this.MsgGetOutClick(sender, e);
        }

        private void toolSMI_Load_Click(object sender, EventArgs e)
        {
            this.MsgLoadClick(sender, e);
        }

        private void panel1_SizeChanged(object sender, EventArgs e)
        {
            this.splitContainer1.Panel1.Refresh();
            this.splitContainer2.Panel1.Refresh();
            this.splitContainer2.Panel2.Refresh();
        }

        private void ContainerModel_SizeChanged(object sender, EventArgs e)
        {
            splitContainer1_Panel1_SizeChanged(sender, e);
            splitContainer2_Panel1_SizeChanged(sender, e);
            splitContainer2_Panel2_SizeChanged(sender, e);
        }
        #endregion

        #region 接口
        /**
         * 功能：显示容器模型视图
         * 
         * */
        public void ShowCmwById(XmlDocument doc, string sitecode)
        {
            FridgeModel.RefreshLabel("立式冰箱");
            ShelfModel.RefreshLabel("");
            BoxModel.RefreshLabel("盒子");
            FridgeModel fridge = null;
            BoxModel box = null;
            ShelfModel shelf = null;

            if (doc == null)
                return;
            XmlNode root = doc.SelectSingleNode("Container");
            string id = sitecode.Substring(sitecode.IndexOf('-'));
            string[] s = sitecode.Split('-');
            int count = s.Length;
            if (count == 1)
            {
                foreach (XmlNode xn1 in root)
                {
                    if (xn1.Name == "HorizontalFridge")
                    {
                        fridge = new HorizontalFridge();
                        fridge.ParseXml(xn1);
                    }
                    else if (xn1.Name == "VerticalFridge")
                    {
                        fridge = new VerticalFridge();
                        fridge.ParseXml(xn1);
                    }
                    _fridgeModel = fridge;
                }
            }
            else if (count == 2)
            {
                int temp = 0;
                foreach (XmlNode xn1 in root)
                {
                    if (xn1.Name == "HorizontalFridge")
                    {
                        fridge = new HorizontalFridge();
                        fridge.ParseXml(xn1);
                        temp++;
                    }
                    else if (xn1.Name == "VerticalFridge")
                    {
                        fridge = new VerticalFridge();
                        fridge.ParseXml(xn1);
                        temp++;
                    }
                    _fridgeModel = fridge;
                    if (xn1.Name == "ShelfModel" + id)
                    {
                        shelf = new Entity.ShelfModel();
                        shelf.ParseXml(xn1);
                        _shelfModel = shelf;
                        temp++;
                    }
                    if (temp == 2)
                    {
                        return;
                    }
                }
            }
            else
            {
                int temp = 0;
                foreach (XmlNode xn1 in root)//遍历
                {
                    if (xn1.Name == "HorizontalFridge")
                    {
                        fridge = new HorizontalFridge();
                        fridge.ParseXml(xn1);
                        temp++;
                    }
                    else if (xn1.Name == "VerticalFridge")
                    {
                        fridge = new VerticalFridge();
                        fridge.ParseXml(xn1);
                        temp++;
                    }
                    _fridgeModel = fridge;

                    if (xn1.Name == "ShelfModel" + s[0] + "-" + s[1])
                    {
                        shelf = new Entity.ShelfModel();
                        shelf.ParseXml(xn1);
                        _shelfModel = shelf;
                        temp++;
                    }
                    if (xn1.Name == "BoxModel" + id)
                    {
                        box = new Entity.BoxModel();
                        box.ParseXml(xn1);
                        _boxModel = box;
                        temp++;
                    }
                    if (temp == 3)
                    {
                        return;
                    }
                }
            }
        }

        /**
       * 功能：反序列化
       * 
       * */
        public BaseModel ParseXml(ModelStyle type)
        {
            BaseModel model = null;
            BaseModel shelfmodel = null;
            BaseModel boxmodel = null;

            XmlNode node = this.docmodel.Xml.SelectSingleNode("Container");
            if (node == null)
            {
                return null;
            }

            switch (type)
            {
                case ModelStyle.HorizontalFridge:
                case ModelStyle.VerticalFridge:
                case ModelStyle.LiquidNitrogenJar:
                    foreach (XmlNode xn in node)
                    {
                        if (xn.Name == ModelStyle.VerticalFridge.ToString()
                            || xn.Name == ModelStyle.HorizontalFridge.ToString()
                            || xn.Name == ModelStyle.LiquidNitrogenJar.ToString())
                        {
                            model = CMFactory.GetInstance().CreateModel(xn.Name);
                            model.ParseXml(xn);
                            return model;
                        }
                    }
                    break;
                case ModelStyle.ShelfModel:
                    string strDName = "ShelfModel" + _fridgeModel.ID + "-" + (MouseRow * 10 + MouseColumn).ToString();
                    foreach (XmlNode xn in node)
                    {
                        if (xn.Name == strDName)
                        {
                            shelfmodel = new ShelfModel();
                            shelfmodel.ParseXml(xn);
                            return shelfmodel;
                        }
                    }
                    break;
                case ModelStyle.BoxModel:
                    if (_shelfModel != null)
                    {
                        shelfmodel = _shelfModel;
                    }
                    string BName = "BoxModel" + shelfmodel.ID + "-" + (MouseRow * 10 + MouseColumn).ToString();
                    foreach (XmlNode xn in node)
                    {
                        if (xn.Name == BName)
                        {
                            boxmodel = new BoxModel();
                            boxmodel.ParseXml(xn);
                            return boxmodel;
                        }
                    }
                    break;
            }
            return null;
        }
       
        //存入或者删除标本时，修改对应容器容量
       /* public void SetModelPercent(string BoxName, string ShelfName, int row, int column, bool IsAdd)
        {
            this.docmodel.InitModelPercent();

            XmlNode root = this.docmodel.Xml.SelectSingleNode("Container");
            XmlElement element = null;

            if (root == null)
            {
                return;
            }
            string strname = "Specimen-" + BoxName + "-" + ((row + 1) * 10 + column + 1).ToString();
            XmlNode xroot = root.SelectSingleNode(strname);

            if (xroot == null)
            {
                element = this.docmodel.Xml.CreateElement(strname);
                root.AppendChild(element);
            }
            else
            {
                element = (XmlElement)xroot;
            }
            if (IsAdd)
            {
                element.SetAttribute("Row", row.ToString());
                element.SetAttribute("Column", column.ToString());
                element.SetAttribute("IsLoaded", "true");

                //bool[,] IsFull = _BoxIsFull;
                //IsFull[row, column] = true;
                //_BoxIsFull = IsFull;
            }
            else
            {
                element.SetAttribute("Row", row.ToString());
                element.SetAttribute("Column", column.ToString());
                element.SetAttribute("IsLoaded", "false");
                //root.RemoveChild(element);

                //bool[,] IsFull = _BoxIsFull;
                //IsFull[row, column] = false;
                //_BoxIsFull = IsFull;
            }

            //this.splitContainer2.Panel2.Refresh();

            foreach (XmlNode xn in root)
            {
                element = (XmlElement)xn;
                if (xn.Name == "BoxModel" + BoxName)
                {
                    int conut = Convert.ToInt32(element.GetAttribute("SpecimenCount"));
                    if (IsAdd)
                    {
                        conut += 1;
                    }
                    else
                    {
                        conut -= 1;
                        if (conut < 0)
                            conut = 0;
                    }
                    element.SetAttribute("SpecimenCount", conut.ToString());
                }
                else if (xn.Name == "ShelfModel" + ShelfName)
                {
                    int conut = Convert.ToInt32(element.GetAttribute("SpecimenCount"));
                    if (IsAdd)
                    {
                        conut += 1;
                    }
                    else
                    {
                        conut -= 1;
                        if (conut < 0)
                            conut = 0;
                    }
                    element.SetAttribute("SpecimenCount", conut.ToString());
                }
            }
            if (FridgeModel != null)
            {
                FridgeModel.GetModelPercent(FridgeModel.ID);

            }
            if (ShelfModel != null)
            {
                ShelfModel.GetModelPercent(ShelfModel.ID);
            }
            if (BoxModel != null)
            {
                ShelfModel.GetModelPercent(BoxModel.ID);
            }
        }*/
        #endregion

        public void RefreshAllLabel()
        {
            if (FridgeModel != null)
            {
                this.FridgeModel.RefreshLabel("立式冰箱");
            }

            if (ShelfModel != null)
            {
                this.ShelfModel.RefreshLabel("架子");
            }
            if (BoxModel != null)
            {
                this.BoxModel.RefreshLabel("盒子");
            }
        }

        public void Refresh(ModelStyle type)
        {
            switch (type)
            {
                case ModelStyle.BoxModel:
                    splitContainer2.Panel2.Refresh();
                    break;
                case ModelStyle.ShelfModel:
                    splitContainer2.Panel1.Refresh();
                    break;
                case ModelStyle.VerticalFridge:
                case ModelStyle.HorizontalFridge:
                case ModelStyle.LiquidNitrogenJar:
                    splitContainer1.Panel1.Refresh();
                    break;
                default:
                    break;
            }
        }
    }
}